package cn.yeziji.forum.common.websocket;

import lombok.Data;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Date;

/**
 * 私聊房间
 *
 * <p>chatroom 利用字符排序的方式，确保 to&from 和 from&to 都属于一样的聊天房间名
 *
 * @author gzkemays
 * @since 2022/3/26 23:55
 */
@Data
public class Chatroom {
  public static String SYSTEM = "system";
  public static String PRIVATE = "private";
  public static String PRIVATE_CLOSE = "private-close";
  public static String ALL = "publish";
  public static String ALL_CLOSE = "publish-close";
  public static String USER_MSG = "user-msg";
  public static String USER_RECORDS = "user-records";
  public static String KEY = "key";
  public static String AND = "&";
  public static String SYSTEM_FROM = "系统消息";
  String chatroom;
  String key;
  String from;
  String to;
  String msg;
  String token;
  String avatar;
  Date createTime;
  Date updateTime;

  public static Chatroom buildSystemChatroom(String to, String msg) {
    Chatroom cr = new Chatroom();
    cr.setKey(SYSTEM);
    cr.setTo(to);
    cr.setFrom(SYSTEM_FROM);
    cr.setMsg(msg);
    cr.reBuildChatroomName();
    cr.setCreateTime(new Date());
    return cr;
  }

  public void reBuildChatroomName() {
    if (StringUtils.hasText(to) && StringUtils.hasText(from)) {
      String[] split = (to + AND + from).split(AND);
      Arrays.sort(split);
      chatroom = split[0] + AND + split[1];
      return;
    }
    throw new IllegalArgumentException("参数有误");
  }

  public void buildChatroom() {
    if (chatroom != null && chatroom.contains(AND) && key.equals(PRIVATE)) {
      String[] split = chatroom.split(AND);
      Arrays.sort(split);
      chatroom = split[0] + AND + split[1];
    }
    if (chatroom == null) {
      String[] split = (to + AND + from).split(AND);
      Arrays.sort(split);
      chatroom = split[0] + AND + split[1];
    }
  }
}
